package com.example.demo.thread;

import java.util.concurrent.*;

/**
 * 项目名称：hello-6
 * 类 名 称：TestCallable
 * 类 描 述：使用callable方式创建线程
 * 创建时间：2021/4/24 20:53
 * 创 建 人：wangsheng
 */
public class TestCallable implements Callable<Boolean> {

    private static String name = "";

    @Override
    public Boolean call() {
        for (int i = 1; i <= 100; i++) {

            boolean flag = running(i);
            if (flag) {
                break;
            }
            if (name == "") {
                System.out.println(Thread.currentThread().getName() + "跑了：" + i + "步");
            }
        }
        return true;
    }

    Boolean running(int i) {
        if (!name.equals("")) {
            return true;
        } else {
            if (i == 100) {
                name = Thread.currentThread().getName();
                System.out.println(Thread.currentThread().getName() + "跑完：" + i + "步");
                System.out.println(Thread.currentThread().getName() + "获胜");
                return true;
            } else {
                return false;
            }
        }
    }

    public static void main(String[] args) {
        TestCallable testCallable = new TestCallable();
        ExecutorService ser = Executors.newFixedThreadPool(3);
        Future<Boolean> s1 = ser.submit(testCallable);
        Future<Boolean> s2 = ser.submit(testCallable);
        Future<Boolean> s3 = ser.submit(testCallable);
        try {
            s1.get();
            s2.get();
            s3.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }finally {
            ser.shutdown();
        }


    }
}
